import type { AxiosPromise, Method, AxiosResponse } from 'axios'
import axios from 'axios'
import GlobalLoading from '@/components/Global/Loading'
import kingUrl from '../kingUrl'
import { kingMlhUrl } from '../kingUrl'
import { Toast } from 'antd-mobile'
import type { RequestConfig } from './interface'
import type { AnyObj } from '@/types'
import { getCookie, delCookie, delLocalStorage, getLocalStorage } from '@/storage'
import { history } from 'umi'
import clearStorage from '@/utils/clearStorage'
import postMsgRedirect from '@/utils/postMsgRedirect'

const GlobalLoadingDom = GlobalLoading()

// 请求重复过滤
const requestSet: Set<string> = new Set()

let showMessage = false

// 动画加载队列
let loadingTimer: number | null = null

const Http = axios.create({
    baseURL: kingUrl,
    headers: {
        'Content-Type': 'application/json',
        'X-Client-Type': 'mobile',
        'X-Site-Alias': 'training',
        // 'X-Test-Domain': 'http://career.itc.dev.woczx.com',
        // Authorization: 'Bearer 9G-dNzsjFbAEmQaY6RThVchBeIkubUFa-1680054580',
    },
})

/**
 * 获取请求标识
 * @param config
 * @returns
 */
const getRequestId = (config: RequestConfig): string => {
    let { url, data = {}, params = {} } = config

    // response config 的data或params是被序列号后的数据
    try {
        data = JSON.parse(data)
        params = JSON.parse(params)
    } catch {}

    return encodeURIComponent(`${url}${JSON.stringify(data)}${JSON.stringify(params)}`)
}

/**
 * 显示加载动画
 * @param delay
 */
const showLoading = (delay: number) => {
    if (typeof window !== 'undefined') {
        loadingTimer !== null && window.clearTimeout(loadingTimer)

        loadingTimer = window.setTimeout(() => {
            GlobalLoadingDom.show('正在上传中...')
        }, delay)
    }
}

/**
 * 隐藏动画加载
 */
const hideLoading = () => {
    if (loadingTimer !== null) {
        if (typeof window !== 'undefined') {
            window.clearTimeout(loadingTimer)
        }

        // 关闭加载动画
        GlobalLoadingDom.close()
    }
}

const whiteList = [
    '/o/v1/systems/website',
    '/o/v1/company-enroll',
    '/o/v1/qz-portal/platform-homepage-list',
    '/o/v1/banner',
    '/o/v1/qz-portal/fine-teacher',
    '/o/v1/qz-portal/fine-student',
    '/o/v1/qz-portal/test-eval',
    '/o/v1/systems/info',
    '/oauth/qz-mini-program-urllink',
]
/**
 * 请求拦截器
 */
Http.interceptors.request.use(
    (config: RequestConfig) => {
        const { delayTime = 1000 * 80 } = config

        if (whiteList.includes(config.url as string)) {
            config.baseURL = kingMlhUrl
            const choiceSite = getLocalStorage('CHOOSE_PLATFORM_SITE') || {}
            config.headers['X-Site-Domain'] = choiceSite?.url ? choiceSite?.url : 'https://zhejiang-test.busionline.com'
            delete config.headers['X-Client-Type']
            delete config.headers['X-Site-Alias']
        }

        // 修改请求超时时间
        config.timeout = delayTime
        // 69nDus6tD-nhA9DzZEpJCueBa-1kSG72-1663222822
        /* config.headers.Authorization = `Bearer 69nDus6tD-nhA9DzZEpJCueBa-1kSG72-1663222822`
        console.log(getCookie('TOKEN'))*/
        // 请求头添加token
        if (getCookie('TOKEN') && config.headers) {
            config.headers.Authorization = `Bearer ${getCookie('TOKEN')}`
        }
        console.log(getCookie('PLATFORMTOKEN'))
        // if (getCookie('PLATFORMTOKEN') && config.headers) {
        //     config.headers['Platform-Access-Token'] = `${getCookie('PLATFORMTOKEN')}`
        // }
        // 开启过滤空数据(例如：get请求数据查询)
        if (config.filterEmptyData === true) {
            // 过滤get空数据
            if (config.method?.toLowerCase() === 'get') {
                const filterParams: AnyObj = {}
                for (const key in config.params) {
                    const val = config.params[key]
                    val !== '' && (filterParams[key] = val)
                }
                config.params = filterParams
            }
        }

        // 文件上传
        // 单独处理格式转换、超时设置、加载动画
        if (config.headers && config.headers['Content-Type'] === 'multipart/form-data') {
            const formData = new FormData()
            for (const key in config.data) {
                formData.append(key, config.data[key] as any)
            }
            config.data = formData
            config.timeout = 1000 * 600
            showLoading(delayTime)
        }

        // 重复接口过滤
        // if (config.repeatFilter !== false) {
        //     const requestToken = getRequestId(config as RequestConfig)
        //     // 拦截重复请求，使其处于Promise<pedding>状态
        //     if (requestSet.has(requestToken)) {
        //         return new Promise(() => {})
        //     }
        //     // 存储请求拦截回调函数
        //     requestSet.add(requestToken)
        // }

        return config
    },
    error => {
        // 请求错误处理
        // 配置err显示
        Promise.reject(error)
    },
)

Http.interceptors.response.use(
    res => {
        const requestToken = getRequestId(res.config as RequestConfig)
        // 移除已完成的请求，避免占位
        requestSet.delete(requestToken)
        // 清空加载动画
        hideLoading()
        return Promise.resolve(res)
    },
    error => {
        console.dir(error)
        // 清空加载动画
        hideLoading()
        // 响应错误处理
        const { data = {}, status }: { data: any; status: number } = error.response || {}
        const { config } = error
        const requestToken = getRequestId(config)
        // 移除已完成的请求，避免占位
        requestSet.delete(requestToken)
        // 请求超时
        if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
            Toast.show({
                icon: 'fail',
                content: '请求超时,请稍后再试!',
            })
            return Promise.reject('请求超时,请稍后再试!')
        }
        // 服务端数据处理异常
        if (status === undefined) {
            // Toast.show('系统繁忙')
            return Promise.reject({
                message: '系统繁忙',
                data: { message: '系统繁忙' },
            })
        }

        switch (status) {
            case 400:
                break

            case 401: {
                postMsgRedirect()
                // /** 用户未认证 */
                // if (data.code === 1) {
                //     history.push('/auth/intercept')
                //     return
                // }
                // /** 重复跳转到登录页 */
                // if (history.location.pathname !== '/login/verification') {
                //     const { search } = history.location
                //     /** 过滤一些不需要 */
                //     const blackPath = ['/personalinfo', '/login', '/auth']
                //     if (
                //         blackPath.filter(bpath => history?.location?.pathname?.startsWith(bpath))
                //             .length === 0
                //     ) {
                //         localStorage.setItem('err_path', history.location.pathname + search)
                //     }
                //     history.replace('/login/verification')
                // }
                // showMessage &&
                //     Toast.show({
                //         content: '请先登录',
                //     })
                // showMessage = false
                clearStorage()
                break
            }

            case 404:
                break

            default:
        }
        console.log(error.response)
        if (!config.noMsg && status !== 401) {
            if (Array.isArray(data)) {
                if (data[0].field === 'mobile_register' || data[0].field === 'mobile_success' || data[0].field === 'mobile_exists') {
                } else {
                    Toast.show({
                        content: data[0].message,
                    })
                }
            } else {
                if (typeof data === 'object') {
                    Toast.show({
                        content: data.message,
                    })
                }
            }
        }

        return Promise.reject(error.response)
    },
)

const baseRequest = <T, K>(url: string, method: Method, data: T, config?: RequestConfig): AxiosPromise<K | any> =>
    Http.request<RequestConfig, AxiosResponse<K>>({
        ...config,
        url,
        method,
        [['get', 'GET'].includes(method) ? 'params' : 'data']: data,
    })

/**
 * get请求
 * @param url 请求地址
 * @param param 请求地址
 * @returns {Promise<AxiosResponse>}
 */
export const getData = <T, K>(url: string, param?: any, config = {}) => {
    return baseRequest<T, K>(url, 'get', param || {}, config)
}

/**
 * post请求
 * @param type 请求方式
 * @param url 请求地址
 * @param param 请求地址
 * @returns {Promise<AxiosResponse>}
 */
export const postData = (url: string, param = {}, config = {}) => {
    return baseRequest(url, 'post', param, config)
}

/**
 * 上传文件请求
 * @param urlLink 请求地址
 * @param param 表单数据{Object}内部必须file键值对
 * @returns {Promise<AxiosResponse>}
 */
export const postFile = (url: string, param: any) => {
    let fileData = new FormData()
    for (let key in param) {
        fileData.append(key, param[key])
    }
    //通过append向form对象添加数据
    return baseRequest(url, 'post', fileData, {})
}

/**
 * delete请求
 * @param type 请求方式
 * @param url 请求地址
 * @param param 请求地址
 * @returns {Promise<AxiosResponse>}
 */
export const deleteData = (url: string, param = {}) => {
    return baseRequest(url, 'delete', param, {})
}

/**
 * put请求
 * @param type 请求方式
 * @param url 请求地址
 * @param param 请求地址
 * @returns {Promise<AxiosResponse>}
 */
export const putData = (url: string, param = {}) => {
    return baseRequest(url, 'put', param, {})
}

export default baseRequest
